package com.jy.datapipeline.common.util;

import com.jy.datapipeline.export.properties.JdbcProperties;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @类名 JdbcUtil
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/8/8 22:01
 * @版本 1.0
 */
public class JdbcUtil {

    public static int defaultCapacity = 10;

    private static final Queue<Connection> CONNECTION_QUEUE = new ArrayBlockingQueue<>(defaultCapacity);

    private static String driver;

    private static String url;

    private static String username;

    private static String password;

    static {
        try {
            JdbcUtil.initJdbc();
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void initJdbc() {
        JdbcProperties jdbcProperties = BeanFactoryUtil.getBean(JdbcProperties.class);
        url = jdbcProperties.getUrl();
        driver = jdbcProperties.getType();
        username = jdbcProperties.getUsername();
        password = jdbcProperties.getPassword();
    }

    @SneakyThrows
    public static Connection createConnection() {
        initJdbc();
        Connection connection = DriverManager.getConnection(url, username, password);
        CONNECTION_QUEUE.offer(connection);
        return connection;
    }

    public static class JdbcConnectionPool {

        private JdbcConnectionPool() {
        }

        private static JdbcConnectionPool jdbcConnectionPool = null;

        public static synchronized JdbcConnectionPool getInstance(Integer... capacity) {
            if (jdbcConnectionPool == null) {
                jdbcConnectionPool = new JdbcConnectionPool();
            }
            if (capacity.length > 0) {
                defaultCapacity = capacity[0];
            }
            return jdbcConnectionPool;
        }

        public Connection getConnection() {
            if (CONNECTION_QUEUE.isEmpty()) {
                return JdbcUtil.createConnection();
            } else {
                return CONNECTION_QUEUE.poll();
            }
        }

        @SneakyThrows
        public void release(Connection connection, PreparedStatement preparedStatement) {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                CONNECTION_QUEUE.remove(connection);
                connection.close();
            }
        }
    }
}
